from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, 
                             QPushButton, QScrollArea, QFrame, QLabel)
from PyQt6.QtCore import Qt, pyqtSignal, QSize
from PyQt6.QtGui import QFont, QPalette, QColor
from datetime import datetime

class ChatBubble(QFrame):
    def __init__(self, content: str, is_user: bool = True, parent=None):
        super().__init__(parent)
        self.content = content
        self.is_user = is_user
        self.init_ui()
        
    def init_ui(self):
        # 创建主布局
        main_layout = QHBoxLayout()
        main_layout.setContentsMargins(8, 4, 8, 4)
        main_layout.setSpacing(8)
        self.setLayout(main_layout)
        
        # 创建消息容器
        message_container = QFrame()
        message_layout = QVBoxLayout()
        message_layout.setContentsMargins(12, 8, 12, 8)
        message_container.setLayout(message_layout)
        
        # 创建文本显示区域
        self.text_label = QLabel()
        self.text_label.setWordWrap(True)
        self.text_label.setStyleSheet("""
            QLabel {
                background-color: transparent;
                border: none;
                color: #FFFFFF;
                padding: 0px;
                font-size: 14px;
                line-height: 1.6;
            }
        """)
        
        # 设置消息容器样式
        if self.is_user:
            message_container.setStyleSheet("""
                QFrame {
                    background-color: #2196F3;
                    border-radius: 16px;
                    border-top-right-radius: 4px;
                    min-width: 100px;
                }
            """)
            main_layout.addStretch(1)
            main_layout.addWidget(message_container)
        else:
            message_container.setStyleSheet("""
                QFrame {
                    background-color: #2D2D2D;
                    border-radius: 16px;
                    border-top-left-radius: 4px;
                    min-width: 100px;
                }
            """)
            main_layout.addWidget(message_container)
            main_layout.addStretch(1)
        
        message_layout.addWidget(self.text_label)
        
        # 显示内容
        self.text_label.setText(self.content)
        self.adjust_size()
    
    def adjust_size(self):
        """调整消息大小"""
        # 获取父容器宽度
        parent_width = self.parent().width() if self.parent() else 600
        
        # 设置最大宽度为父容器宽度减去边距
        max_width = parent_width - 32  # 32是左右边距的总和
        
        # 设置宽度
        self.setMaximumWidth(max_width)
        
        # 设置最小宽度
        self.setMinimumWidth(100)
        
        # 让 QLabel 自动调整高度
        self.text_label.setMinimumWidth(max_width - 24)  # 减去内边距
        self.text_label.setMaximumWidth(max_width - 24)  # 减去内边距

class ChatPanel(QWidget):
    message_sent = pyqtSignal(str)  # 消息发送信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        self.setup_styles()
        
    def setup_styles(self):
        """设置全局样式"""
        self.setStyleSheet("""
            QWidget {
                background-color: #1E1E1E;
                color: #FFFFFF;
            }
            QTextEdit {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
                padding: 8px;
                color: #FFFFFF;
            }
            QPushButton {
                background-color: #2196F3;
                color: #FFFFFF;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #1976D2;
            }
            QPushButton:pressed {
                background-color: #1565C0;
            }
            QScrollArea {
                border: none;
                background-color: transparent;
            }
        """)
    
    def init_ui(self):
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        self.setLayout(main_layout)
        
        # 聊天记录区域
        self.chat_area = QScrollArea()
        self.chat_area.setWidgetResizable(True)
        self.chat_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #1E1E1E;
            }
            QScrollBar:vertical {
                border: none;
                background-color: #2D2D2D;
                width: 6px;
                margin: 0px;
            }
            QScrollBar::handle:vertical {
                background-color: #404040;
                min-height: 20px;
                border-radius: 3px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        
        # 聊天内容容器
        self.chat_widget = QWidget()
        self.chat_widget.setStyleSheet("""
            QWidget {
                background-color: #1E1E1E;
            }
        """)
        self.chat_layout = QVBoxLayout()
        self.chat_layout.setContentsMargins(16, 16, 16, 16)
        self.chat_layout.setSpacing(12)
        self.chat_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.chat_widget.setLayout(self.chat_layout)
        self.chat_area.setWidget(self.chat_widget)
        main_layout.addWidget(self.chat_area, stretch=1)
        
        # 输入区域容器
        input_container = QFrame()
        input_container.setStyleSheet("""
            QFrame {
                background-color: #2D2D2D;
                border-top: 1px solid #404040;
            }
        """)
        input_layout = QHBoxLayout()
        input_layout.setContentsMargins(8, 4, 8, 4)
        input_layout.setSpacing(8)
        input_container.setLayout(input_layout)
        
        # 输入框容器
        input_box_container = QFrame()
        input_box_container.setStyleSheet("""
            QFrame {
                background-color: #1E1E1E;
                border: 1px solid #404040;
                border-radius: 4px;
            }
        """)
        input_box_layout = QVBoxLayout()
        input_box_layout.setContentsMargins(0, 0, 0, 0)
        input_box_container.setLayout(input_box_layout)
        
        # 输入框
        self.input_box = QTextEdit()
        self.input_box.setPlaceholderText("输入消息... (按Enter发送，Ctrl+Enter换行)")
        self.input_box.setMaximumHeight(36)
        self.input_box.setMinimumHeight(36)
        self.input_box.setStyleSheet("""
            QTextEdit {
                background-color: transparent;
                border: none;
                padding: 4px 8px;
                color: #FFFFFF;
                font-size: 14px;
                line-height: 1.4;
            }
        """)
        self.input_box.textChanged.connect(self.adjust_input_height)
        self.input_box.installEventFilter(self)
        input_box_layout.addWidget(self.input_box)
        
        input_layout.addWidget(input_box_container, stretch=1)
        
        # 发送按钮
        self.send_button = QPushButton("发送")
        self.send_button.setFixedSize(64, 28)
        self.send_button.setStyleSheet("""
            QPushButton {
                background-color: #2196F3;
                color: #FFFFFF;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #1976D2;
            }
            QPushButton:pressed {
                background-color: #1565C0;
            }
        """)
        self.send_button.clicked.connect(self.send_message)
        input_layout.addWidget(self.send_button)
        
        main_layout.addWidget(input_container)
    
    def adjust_input_height(self):
        """根据内容调整输入框高度"""
        doc_height = self.input_box.document().size().height()
        new_height = min(max(doc_height + 8, 36), 120)  # 最大高度120px
        self.input_box.setMaximumHeight(int(new_height))
    
    def eventFilter(self, obj, event):
        """事件过滤器，处理输入框的按键事件"""
        if obj == self.input_box and event.type() == event.Type.KeyPress:
            if event.key() == Qt.Key.Key_Return:
                if event.modifiers() == Qt.KeyboardModifier.ControlModifier:
                    # Ctrl+Enter 换行
                    return False
                else:
                    # Enter 发送消息
                    self.send_message()
                    return True
        return super().eventFilter(obj, event)
    
    def send_message(self):
        """发送消息"""
        message = self.input_box.toPlainText().strip()
        if not message:
            return
        
        # 添加用户消息
        self.add_message(message, True)
        self.input_box.clear()
        
        # 发送信号
        self.message_sent.emit(message)
    
    def add_message(self, content: str, is_user: bool = True):
        """添加消息"""
        message = ChatBubble(content, is_user)
        self.chat_layout.addWidget(message)
        self.scroll_to_bottom()
    
    def scroll_to_bottom(self):
        """滚动到底部"""
        self.chat_area.verticalScrollBar().setValue(
            self.chat_area.verticalScrollBar().maximum()
        ) 